package com.zdy.demo2;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * Created by 逸足天涯
 * on 3/8/2020.
 */
//实现Callable
// 1.定义返回值，
// 2. 可以跑出异常
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;

    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }
    @Override
    public Boolean call() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downLoader(url, name);
        System.out.println("下载了文件名为：" + name);
        return true;
    }

    //创建下载器类
    class WebDownLoader{
        public void downLoader(String url,String name){
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("IO 异常downLoader方法出现问题");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException,ExecutionException {
        //url 在网上随便找的，可能会失效，自己手动换一个即可
        TestCallable t1 = new TestCallable("https://www.baidu.com/img/dong3_ce6e6a5ce66ab92f491f627981a2f77c.gif","图片1");
        TestCallable t2 = new TestCallable("http://img95.699pic.com/photo/50155/6342.jpg_wh860.jpg!/both/590x400","图片2");
        TestCallable t3 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy96eG9MYWVDSTI4U2dSNUVZTTBlY0UyT1VCdkZBZHo0TUhubFBEaGxjcmJNMnlueG0wWUpqNFBDTGxQS0FuUW1UeHpYTDVqVHlnYnRoM0lQOGVZRjVhZy82NDA?x-oss-process=image/format,png","图片3");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        //关闭服务
        ser.shutdown();
    }

}
